package com.yanqu.road.server.manger.activity.wishpool;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.wishpool.WishPoolBigReward;
import com.yanqu.road.entity.activity.wishpool.WishPoolCommonReward;
import com.yanqu.road.entity.activity.wishpool.WishPoolConfig;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.logic.bussiness.activity.WishPoolActivityBusiness;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.wishpool.WishPoolModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.bulletscreen.ActivityBulletScreenMgr;
import com.yanqu.road.server.manger.activity.newyear2023.FireWorkMgr;
import com.yanqu.road.server.manger.activity.springdinner.SpringDinnerMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.string.StringUtils;

import java.util.*;

public class WishPoolMgr extends TempMgr {

    public static ActivityInfo activityInfo;

    public static WishPoolConfig wishPoolConfig;

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static void reloadActivityData() {
        reloadActivityDataWishPool();
        reloadActivityDataSpringDinner();
        reloadActivityDataFireWork();
    }

    public static void reloadActivityDataSpringDinner() {
        // 粘液饭弹幕也去初始化一下
        if(SpringDinnerMgr.getActivityInfo() != null){
            ActivityBulletScreenMgr.initOrReloadMsgData(SpringDinnerMgr.getActivityInfo());
        }
    }

    public static void reloadActivityDataFireWork() {
        // 烟花祈愿弹幕也去初始化一下
        if(FireWorkMgr.getTypeActivity(2) != null){
            ActivityBulletScreenMgr.initOrReloadMsgData(FireWorkMgr.getTypeActivity(2));
        }
    }

    public static void reloadActivityDataWishPool() {
        getLogger().info("reload WishPool start");

        // 获取进行中的许愿池活动
        ActivityInfo inShowTimeActivityInfo = null;
        Map<Integer, ActivityInfo> inShowTimeActivityInfoMap = NormalActivityMgr.getShowTimeActivityInfoMap();
        for (ActivityInfo tmpActivityInfo : inShowTimeActivityInfoMap.values()) {
            if (tmpActivityInfo.getType() == eActivityType.WishPoolActivity.getValue()) {
                inShowTimeActivityInfo = tmpActivityInfo;
                break;
            }
        }
        if (inShowTimeActivityInfo == null) {
            getLogger().info("no WishPool in show time");
            return;
        }

        // 获取许愿池大奖
        List<WishPoolBigReward> bigRewardList = WishPoolActivityBusiness.getWishPoolBigRewardList(inShowTimeActivityInfo.getActivityId());

        // 校验参数
        if (!checkActivityParam(inShowTimeActivityInfo, bigRewardList)) {
            getLogger().error("WishPool config error!!!");
            return;
        }

        // 解析参数
        WishPoolConfig tmpWishPoolConfig = new WishPoolConfig();
        tmpWishPoolConfig.setOneTimesWishValue(Integer.valueOf(inShowTimeActivityInfo.getParam5()));
        List<WishPoolCommonReward> commonRewardList = new ArrayList<>();
        for (String tmpReward : StringUtils.stringToStringList(inShowTimeActivityInfo.getParam6(), "\\|")) {
            List<String> tmpRewardSplit = StringUtils.stringToStringList(tmpReward, ";");
            WishPoolCommonReward commonReward = new WishPoolCommonReward();
            commonReward.setReward(tmpRewardSplit.get(0));
            commonReward.setWeight(Integer.valueOf(tmpRewardSplit.get(1)));
            commonRewardList.add(commonReward);
        }
        tmpWishPoolConfig.setCommonRewardList(commonRewardList);
        tmpWishPoolConfig.setBigRewardList(bigRewardList);

        // 弹幕数据
        ActivityBulletScreenMgr.initOrReloadMsgData(inShowTimeActivityInfo);

        wishPoolConfig = tmpWishPoolConfig;
        activityInfo = inShowTimeActivityInfo;

        // 重置玩家数据
        resetPlayerData();
    }

    private static boolean checkActivityParam(ActivityInfo activityInfo, List<WishPoolBigReward> bigRewardList) {
        String paramName = "";
        try {
            paramName = "每次许愿值（param5）";
            if (Integer.parseInt(activityInfo.getParam5()) <= 0) {
                throw new Exception();
            }
            paramName = "普通奖励（param6）";
            List<String> stringList = StringUtils.stringToStringList(activityInfo.getParam6(), "\\|"); // 10001=10;10|10002=5;20
            if (stringList.size() <= 0) {
                throw new Exception();
            }
            for (String tmp : stringList) {
                List<String> stringList1 = StringUtils.stringToStringList(tmp, ";"); // 10001=10;10
                List<String> stringList2 = StringUtils.stringToStringList(stringList1.get(0), "="); // 10001=10
                if (stringList1.size() != 2
                        || Integer.valueOf(stringList1.get(1)) <= 0
                        || stringList2.size() != 2
                        || Integer.valueOf(stringList2.get(0)) <= 0
                        || Integer.valueOf(stringList2.get(1)) <= 0) {
                    throw new Exception();
                }
            }
            paramName = "特殊奖励道具表（t_s_wish_pool）";
            Set<Integer> value = new HashSet<>();
            int lastWishValue = 0;
            for (WishPoolBigReward bigReward : bigRewardList) {
                if (bigReward.getWishValue() <= lastWishValue || !value.add(bigReward.getWishValue())
                        || bigReward.getRewardList().size() <= 0) {
                    throw new Exception();
                }
                for (String tmp : bigReward.getRewardList()) {
                    List<String> tmpList = StringUtils.stringToStringList(tmp, "="); // 10001=10
                    if (tmpList.size() != 2 || Integer.valueOf(tmpList.get(0)) <= 0 || Integer.valueOf(tmpList.get(1)) <= 0) {
                        throw new Exception();
                    }
                }
                lastWishValue = bigReward.getWishValue();
            }

        } catch (Exception e) {
            getLogger().error("许愿池活动参数 {} 错误", paramName);
            return false;
        }
        return true;
    }

    /**
     * 随机获取一个普通奖励
     */
    public static String randomCommonReward() {
        // 总权重
        int sumWeight = 0;
        for (WishPoolCommonReward commonReward : wishPoolConfig.getCommonRewardList()) {
            sumWeight += commonReward.getWeight();
        }
        // 随机值
        int weightIndex = new Random().nextInt(sumWeight);
        // 找对应奖励
        for (WishPoolCommonReward commonReward : wishPoolConfig.getCommonRewardList()) {
            weightIndex = weightIndex - commonReward.getWeight();
            if (weightIndex < 0) {
                return commonReward.getReward();
            }
        }
        // 不可能走到这里
        getLogger().error("wish pool random common reward error!!!");
        return wishPoolConfig.getCommonRewardList().get(0).getReward();
    }

    /**
     * 获取可选奖励List
     */
    public static List<WishPoolBigReward> getBigRewardList() {
        return wishPoolConfig.getBigRewardList();
    }

    /**
     * 是否在活动时间内
     */
    public static boolean isActivityInTime() {
        return ActivityMgr.activityInTime(activityInfo);
    }

    /**
     * 是否在活动展示时间内
     */
    public static boolean isActivityInShowTime() {
        return ActivityMgr.activityInShowTime(activityInfo);
    }

    /**
     * 获取正在进行的活动ID
     *
     * @return 0：没有正在进行的活动，其他：活动ID
     */
    public static int getInShowTimeActivityId() {
        return isActivityInShowTime() ? activityInfo.getActivityId() : 0;
    }

    /**
     * 玩家许愿池每日重置
     */
    private static void resetPlayerData() {
        int inTimeActivityId = WishPoolMgr.getInShowTimeActivityId();
        if (inTimeActivityId == 0) {
            return;
        }
        for (GamePlayer player : GamePlayerMgr.getCopyPlayerMap().values()) {
            if (SystemOpenMgr.systemOpen(player, eSystemId.WishPoolActivity.getValue())) {
                WishPoolModule wishPoolModule = player.getModule(WishPoolModule.class);
                if (wishPoolModule.getUserData() == null
                        || wishPoolModule.getUserData().getActivityId() != inTimeActivityId) { // 防止活动连开
                    wishPoolModule.initUserData(inTimeActivityId);
                }
                wishPoolModule.resetOneDay();
                wishPoolModule.notifyRedHot();
            }
        }
    }

}
